package com.SH.controller;

import com.SH.pojo.User;
import com.SH.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    //登录
    @PostMapping("/login")
    public String Login(User user, Model model,HttpSession session){
        if(user.getUsername().isEmpty()||user.getPassword().isEmpty()){
            model.addAttribute("m","用户名密码不能为空");
            return "login";
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        try {
            subject.login(token);
        }catch (UnknownAccountException e){ //用户名不存在
            model.addAttribute("m","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("m","密码错误");
            return "login";
        }
        User currentUser = (User)subject.getPrincipal();
        session.setAttribute("user",currentUser);
        return "index";
    }
    //注册
    @PostMapping("/register")
    public String Register(User user, Model model){
        System.out.println(user);
        if(user.getUsername().isEmpty()||user.getPassword().isEmpty()) {
            model.addAttribute("msg", "信息格式有误！");
            return "register";
        }
        userService.addUser(user);
        model.addAttribute("msg","注册成功!");
        return "login";
    }

    @GetMapping("/logout")
    public String Logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }
}
